package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"king/kingrpc/internal/svc"
	"king/kingrpc/kingrpc"
	"king/model/cache"
	"king/model/mysql"
	"time"
)

type ProductAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductAddLogic {
	return &ProductAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProductAddLogic) ProductAdd(in *kingrpc.ProductAddRequest) (*kingrpc.ProductAddResponse, error) {
	// 参数验证
	if in.Title == "" || in.Price < 0 || in.Stock < 0 || in.Sales < 0 {
		return nil, fmt.Errorf("商品字段不能为空")
	}

	// 构建商品实体并保存到数据库
	products := mysql.Product{
		Title: in.Title,
		Price: float64(in.Price),
		Stock: in.Stock,
		Sales: in.Sales,
		Image: in.Image,
	}
	mysql.DB.Create(&products)
	// 缓存商品信息
	key := fmt.Sprintf("productId:%d", products.ID)
	marshal, _ := json.Marshal(products)
	cache.Rdb.Set(l.ctx, key, marshal, time.Minute*30)
	//虚拟库存
	cache.SyncStock(int(products.ID), int(products.Stock))
	return &kingrpc.ProductAddResponse{Id: int64(products.ID)}, nil
}
